<script setup lang="ts">


import {message} from "ant-design-vue";
import dayjs from "dayjs";
import moment from "moment";
import {getCurrentInstance, nextTick, watch} from "vue";
import {ref} from "vue-demi";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import {searchAnalyzeInterception} from "~/utils/interception/sycm/searchAnalyzeInterception";
import Trans from "../../../../utils/sycm/trans";
import EChart from "../../echart.vue";

const {proxy} = getCurrentInstance();
const state = reactive<any>({
  loginVisible: false,
  visible: false,
  showZs: false,
  indexes: ['seIpvUvHits'],
  data: [],
  keyword: '',
  startDate: '',
  endDate: '',
  dateType: 'day',
  showChart: false,
});
const options = ref<any>();
const indexesMap: any = {
  seIpvUvHits: ['搜索人气', '搜索人数', true],
  sePvIndex: ['搜索热度', '搜索次数', true],
  clickHits: ['点击人气', '点击人数', true],
  clickHot: ['点击热度', '点击次数', true],
  clickRate: ['点击率', '点击率', false],
  tradeIndex: ['交易指数', '交易金额', true],
  payConvRate: ['支付转化率', '支付转化率', false],
};
const $req = proxy.$req;
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = () => {
  if (isLogin({
    emit: () => {
      state.loginVisible = true;
    }
  }, __option)) {
    state.data = $req.getResponse(searchAnalyzeInterception[1]);
    if (!state.data) {
      message.error('数据获取失败，请重试~');
    }
    console.log(state.data);
    state.visible = true;
    let startDate, endDate;
    const dates = state.data.__options.params.dateRange.split('|');
    state.dateType = state.data.__options.params.dateType;
    startDate = dates[0];
    endDate = dates[1];
    if (dates[0] === dates[1]) {
      let length = state.data.data.self.seIpvUvHits.length - 1;
      // 倒推出开始日期
      startDate = moment(endDate).add(-length, 'days').format('YYYY-MM-DD');
    }
    state.keyword = state.data.__options.params.keyword;
    state.startDate = startDate;
    state.endDate = endDate;
    calcTableData();
    calcEchartOptions();
  }
}
// 表格数据
const tableData = ref([]);
const calcEchartOptions = async () => {
  state.showChart = false;
// 整理echart 统计图数据
  let datesArray = [];

  if (state.dateType === 'day') {
    let date = moment(state.startDate);
    while (date.format('YYYY-MM-DD') <= state.endDate) {
      datesArray.push(date.format('YYYY-MM-DD'));
      date = date.add(1, 'days');
    }
  } else if (state.dateType == 'week') {
    datesArray = await SYCM.getInternalFiberData('#sycm-mc-mq-search-trend > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content > div > div.alife-one-design-sycm-indexes-trend-chart-container.alife-one-design-sycm-indexes-trend-chart-container-seIpvUvHits > div > div > div > div > div > svg > g.recharts-layer.recharts-cartesian-axis.recharts-xAxis.xAxis > g', 'memoizedProps.children[0]._owner.memoizedProps.domain') || [];
  }
  let echartData: any = {};
  for (let key in indexesMap) {
    if (state.indexes.includes(key)) {
      let data = [...state.data.data.self[key]];
      if (indexesMap[key][2]) {
        // 指数数据
        if (!state.showZs) { // 真实数据
          data = data.map((item: number) => Trans.number(item));
        } else {
          data = data.map((item) => item.toFixed(2));
        }
      } else {
        // 百分比数据
        data = data.map((item: number) => (item * 100).toFixed(2))
      }
      echartData[key] = {
        name: state.keyword + '-' + (state.showZs ? indexesMap[key][0] : indexesMap[key][1]),
        data: data,
        type: 'line',
        smooth: true,
        showSymbol: false,
      };
    }
  }
  options.value = {
    // x轴数据 y轴值 只渲染选中的数据 选中的数据在state.indexes中
    xAxis: {
      type: 'category',
      data: datesArray,
    },
    yAxis: {
      type: 'value',
    },

    //保存图片
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {
          show: true,
          name: state.keyword + '搜索词趋势',
        },
      },
    },
    // 提示框
    tooltip: {
      trigger: 'axis',
      // formatter: function (params: any) {
      //   let str = params[0].axisValue + '<br/>';
      //   params.forEach((item: any) => {
      //     str += item.seriesName + '：' + item.value + '<br/>';
      //   });
      //   return str;
      // },
    },
    // 去掉间距
    // grid: {
    //   left: '3%',
    //   right: '4%',
    //   bottom: '0',
    //   top: '3%',
    //   containLabel: true,
    // },
    legend: {
      data: state.indexes.map((item: string) => indexesMap[item][0]),
    },
    series: Object.values(echartData),
  };
  nextTick(() => {
    state.showChart = true;
  });
}
const columns = ref<any>([]);
const calcTableData = () => {
  // 整理表格数据
  // 计算columns 包含日期 关键字 所有指标
  let otherIndexes = [];
  for (const indexesMapKey in indexesMap) {
    let item = indexesMap[indexesMapKey];
    let key = indexesMapKey;
    if (!item[2]) {
      otherIndexes.push({
        title: state.showZs ? item[0] : item[1],
        dataIndex: key,
        key: key,
        width: 120,
        align: 'right',
        sorter: (a: any, b: any) => a[key] - b[key],
        dataType: 'customRender',
        render: (text: any, record: any, index: any) => {
          return text + '%';
        }
      });
    } else {
      otherIndexes.push({
        title: state.showZs ? item[0] : item[1],
        dataIndex: key,
        key: key,
        width: 120,
        align: 'center',
        sorter: (a: any, b: any) => a[key] - b[key],
      });
    }
  }
  columns.value = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      fixed: 'left',
      width: 120,
      sorter: (a: any, b: any) => a.date.replaceAll('-', '') - b.date.replaceAll('-', ''),
      defaultSortOrder: 'descend',
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
      key: 'keyword',
      fixed: 'left',
      width: 120,
    },
    ...otherIndexes,
  ];
  // 计算表格数据
  let tableDataArray = [];
  let datesArray = [];
  let date = moment(state.startDate);
  while (date.format('YYYY-MM-DD') <= state.endDate) {
    datesArray.push(date.format('YYYY-MM-DD'));
    date = date.add(1, 'days');
  }
  for (let i = 0; i < datesArray.length; i++) {
    let item: any = {
      date: datesArray[i],
      keyword: state.keyword,
    };
    for (let key in indexesMap) {
      if (state.showZs) {
        if (indexesMap[key][2]) {
          item[key] = state.data.data.self[key][i].toFixed(2);
        } else {
          item[key] = (state.data.data.self[key][i] * 100).toFixed(2);
        }
      } else {
        if (indexesMap[key][2]) {
          // 指数转换
          item[key] = Trans.number(state.data.data.self[key][i]);
        } else {
          // 百分比转换
          item[key] = (state.data.data.self[key][i] * 100).toFixed(2);
        }
      }
    }
    tableDataArray.push(item);
  }
  tableData.value = tableDataArray;
}
const toggleIndexes = (key: string) => {
  if (state.indexes.includes(key)) {
    // 从indexes 中删除 key
    if (state.indexes.length === 1) {
      message.error('至少选择一个指标!');
      return;
    }
    state.indexes = state.indexes.filter(item => item !== key);
  } else {
    // 添加 key 到 indexes
    state.indexes.push(key);
  }
}
watch(() => state.indexes, () => {
  calcEchartOptions();
}, {deep: true});
watch(() => state.showZs, () => {
  calcEchartOptions();
  calcTableData();
});
</script>

<template>
  <base-app>
    <a-button-group>
      <user style="margin-right: 0"/>
      <a-button size="small" @click="handle" type="primary">一键转化</a-button>
    </a-button-group>
    <custom-modal title="市场-搜索分析-搜索词趋势" v-model:visible="state.visible" width="97%"
                  style="top: 20px;"
    >
      <template #headerRight>
        <s-y-c-m-custom-modal-header-notice/>
        <div style="display: inline-block;padding-left: 10px;">
          显示指数
          <a-checkbox v-model:checked="state.showZs"/>
        </div>
      </template>
      <div style="max-height: calc(100vh - 150px);overflow-y: auto;">
        <a-row :gutter="20" class="tabs" style="padding-top: 10px;margin-left: 0;margin-right: 0;">
          <a-col :span="3" v-for="(d,key) in indexesMap" :key="key">
            <div class="tab-item" :class="{
            active:state.indexes.includes(key)
          }"
                 @click="toggleIndexes(key)"
            >
              {{ state.showZs ? d[0] : d[1] }}
            </div>
          </a-col>
        </a-row>
        <a-spin v-if="!state.showChart">
          <div style="height: 300px;"></div>
        </a-spin>
        <e-chart v-if="state.showChart" :options="options" style="height: 300px;"/>
        <base-table :data-source="tableData" :columns="columns" table-name="市场-搜索分析-搜索词趋势" size="small"
                    :scroll="{
          y:500,
        }"
        />
      </div>
    </custom-modal>
    <user-login-modal v-model:login-visible="state.loginVisible"/>
  </base-app>
</template>

<style lang="less" scoped>
.tabs {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

  .tab-item {
    padding: 10px 10px;
    border-radius: 5px;
    cursor: pointer;
    border: 2px solid #e8e8e8;
    margin-bottom: 10px;
    background-color: #fff;
    text-align: center;

    &.active {
      background-color: #fff;
      border: 2px solid #0079fe;
    }

    &:hover {
      background-color: #fff;
      border: 2px solid #0079fe;
      // 阴影
      box-shadow: 0 0 10px #eee;
    }
  }
}
</style>
